from django.db import migrations, models
import django.db.models.deletion
import timescale.db.models.fields


def set_cycling_sequence(apps, schema_editor):
    if schema_editor.connection.vendor != 'postgresql':
        return

    SimpleTable = apps.get_model('main', 'SimpleTable')
    schema_editor.execute(f'ALTER SEQUENCE {SimpleTable._meta.db_table}_id_seq CYCLE')


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Entity',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=16)),
            ],
        ),
        migrations.CreateModel(
            name='SimpleTable',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('time', timescale.db.models.fields.TimescaleDateTimeField(interval='1 min')),
                ('data', models.JSONField(default=dict)),
                ('entity', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='main.entity')),
            ],
        ),
        migrations.AddConstraint(
            model_name='entity',
            constraint=models.UniqueConstraint(fields=('name',), name='main__entity__name'),
        ),
        migrations.AddConstraint(
            model_name='simpletable',
            constraint=models.UniqueConstraint(fields=('time', 'entity'), name='main__simpletable__time__entity'),
        ),

        migrations.RunPython(set_cycling_sequence, migrations.RunPython.noop),
    ]
